var $ = layui.$;
/**
 * zmn 渠道-工单照片编辑
 * @author sunlife
 * @since 2021-10-28 11:18:36
 */
layui.define(['index', 'form', 'upload', 'zmnSelect', 'table'], function (exports) {
    let form = layui.form;
    let layer = layui.layer;
    let upload = layui.upload;
    let zmnSelect = layui.zmnSelect;
    let table = layui.table;
    form.render(null, "zmn-form");

    let cols = [[
        {field: 'id', hide: true},
        { field: 'identifier', title: '识别物', width: '30%', align: "center" ,edit: true},
        { field: 'score', title: '置信度', width: '30%', align: "center",edit: true },
        { title: '操作', align: "center", templet: '<div><a class="layui-btn layui-btn-xs" lay-event="del">删除</a></div>' }
    ]];

    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {

        let relateId = json.obj.relateId;
        var url = "/channel/workorder/picture/save/auditDetection.action";

        let tableData = table.cache['zmn-audit-table'] ? table.cache['zmn-audit-table'] : [];

        let standardList = [];

        tableData.forEach((rowData,index,array)=>{
            //执行代码
            if (!rowData) {
                return;
            }
            if (rowData.length < 1) {
                return;
            }
            if (!rowData['identifier'] || !rowData['score']) {
                layer.msg("请完善数据");
            }
            standardList.push(rowData);
        });

        let data = {
            relateId : relateId,
            standardList: standardList
        };

        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (result) {
                if (result.status == 200) {
                    parent.reload(result.message);
                    cancel();
                } else {
                    layui.layer.msg(result.message, {"icon": 2});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        })
        return false;
    });

    function initTable(data) {
        table.render( {
            elem: '#zmn-audit-table',
            toolbar: "#zmn-table-tool",
            defaultToolbar: [],
            cols: cols,
            data: data,
            page: false,
        });
    }
    
    function initEvent() {
        table.on('toolbar(zmn-audit-table)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    let data = table.cache['zmn-audit-table'];
                    if (data.length >= 10) {
                        layer.msg("最多添加10行");
                        break;
                    }
                    data.push({});
                    initTable(data);
                    break;
            }
        });
        table.on('tool(zmn-audit-table)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

           if(layEvent === 'del'){ //删除
                layer.confirm('真的删除行么', function(index){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                });
            }
        });
        table.on('edit(zmn-audit-table)', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
            let value = obj.value.trim();
            let tempVal = obj.value.trim();

            if (obj.field === 'identifier') {
                if (obj.value.length > 256) {
                    layer.msg("长度不得超过256");
                    tempVal = obj.value.substring(0, 256);
                }

                let tableData = table.cache['zmn-audit-table'] ? table.cache['zmn-audit-table'] : [];

                let count = 0;
                tableData.forEach((rowData,index,array)=>{
                    if (!rowData || rowData.length < 1) {
                        return;
                    }
                    if (rowData['identifier'].trim() === value) {
                        count = count + 1;
                    }
                });
                if (count > 1) {
                    layer.msg("不允许有重复名称");
                    tempVal = "";
                }

                obj.update({
                    identifier: tempVal
                });
            } else if (obj.field === 'score') {
                if (value !== "") {
                    let r = /^([1-9]\d{0,9}|0)$/;
                    if (!r.test(value)) {
                        layer.msg('格式内容不正确，请重新输入');
                        tempVal = '';
                    }
                    if (Number(value) > 99) {
                        layer.msg('请输入1~99范围内的整数');
                        tempVal = '';
                    }
                }
                obj.update({
                    score: tempVal
                });
            }

            // 重新渲染
            initTable(table.cache['zmn-audit-table'])
        });
    }

    function init() {
        initTable(json.standardList);
        
        initEvent();
    }

    init();

    // 对外暴露的接口
    exports('channel_workorder_picture_auditStandard', {});
});

// 取消
function cancel() {
    let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index);
}

